package com.ck.ips.service.impl.sys;

import com.ck.common.model.OperationLog;
import com.ck.common.page.PageInfo;
import com.ck.core.constant.DateFormatConstant;
import com.ck.core.constant.PageConstant;
import com.ck.core.util.DateUtils;
import com.ck.ips.dao.sys.OperationLogMapper;
import com.ck.ips.model.vo.sys.OperationLogListVO;
import com.ck.ips.service.sys.OperationLogService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;

/**
 * 日志Service实现类
 */
@Service(value = "operationLogService")
public class OperationLogServiceImpl implements OperationLogService {
    private Logger logger = LoggerFactory.getLogger(OperationLogServiceImpl.class);
    @Autowired
    private OperationLogMapper operationLogMapper;

    /**
     * 保存日志
     *
     * @param operationLog TbOperationLog
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOperationLog(OperationLog operationLog) {
        operationLogMapper.insertOperationLog(operationLog);
    }

    /**
     * 获取操作日志分页列表
     *
     * @param startTime 开始时间
     * @param endTime   接受时间
     * @param pageNum   当前页
     * @param pageSize  每页显示条数
     * @return PageInfo<OperationLogListVO>
     */
    @Override
    public PageInfo<OperationLogListVO> listOperationLogByPage(String startTime, String endTime, String userName,String realName,String ip, Integer pageNum, Integer pageSize) {
        //设置默认值
        if (pageNum == null) {
            pageNum = PageConstant.DEFAULT_PAGE_NUM;
        }
        if (pageSize == null) {
            pageSize = PageConstant.DEFAULT_PAGE_SIZE;
        }
        //把格式化字符串时间转化为Long类型时间戳
        Long longStartTime = null;
        Long longEndTime = null;
        try {
            if (StringUtils.isNotBlank(startTime)) {
                startTime = startTime + DateFormatConstant.H_M_S_MIN;
                longStartTime = DateUtils.stringTimeToLongTimeStamp(startTime, DateFormatConstant.LONG_DATE_FORMAT_STR);
            }
            if (StringUtils.isNotBlank(endTime)) {
                endTime = endTime + DateFormatConstant.H_M_S_MAX;
                longEndTime = DateUtils.stringTimeToLongTimeStamp(endTime, DateFormatConstant.LONG_DATE_FORMAT_STR);
            }
        } catch (ParseException e) {
            logger.error("时间转换失败：" + e.getMessage());
        }
        PageHelper.startPage(pageNum, pageSize);
        Page<OperationLogListVO> operationLogPage = operationLogMapper.listOperationLogByPage(longStartTime, longEndTime,userName,realName,ip);
        //把Page转化为PageInfo
        return PageInfo.convert(operationLogPage);
    }

}
